﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

/// <summary>
/// 命名空间说明 ：诚昊数学 矩阵实验室 
/// Algebra：代数（古希腊）
/// </summary>
namespace MrPoetic.MatLab
{
    using Algebra;
    using System.Data;

    /// 将任意可迭代对象 转换为通用`数据矩阵`
    public sealed partial class DataMatrix
    {
        private static readonly object lockObj = new object();
        internal Tuple<int, int> _matrix;
        internal IEnumerable<object> _ptrObj;
        internal readonly DataTable _Mapper2ADOTable;

        private DataMatrix() { }
        public DataMatrix(IEnumerable<object> dataSoure)
        {
            if (dataSoure == null)
            {
                throw new ArgumentOutOfRangeException("Null DataSource");
            }
            _ptrObj = dataSoure;
            var counts = dataSoure.Count();
            var _t = (int)(Math.Sqrt(counts));
            int x, y;
            x = _t;
            y = counts / _t + (counts % _t == 0 ? 0:1);
            _matrix = new Tuple<int, int>(x, y);
        }
        public DataMatrix(DataTable adoTabel)
        {
            if(_Mapper2ADOTable != null)
            {
                int x = -1, y = -1;
                if(_Mapper2ADOTable.Rows.Count * _Mapper2ADOTable.Columns.Count != 0) {
                    _Mapper2ADOTable = adoTabel;
                    x = adoTabel.Columns.Count;
                    y = _Mapper2ADOTable.Rows.Count;
                }
                _matrix = new Tuple<int, int>(x, y);
            }
            throw new DataException("Null DataAdoTable");
        }
        /// <summary>
        /// 转换任意矩阵为字符串
        /// </summary>
        /// <param name="instance"> 内部实例 instance.create(IEnumerable<int32>) </param>
        /// <returns>M(X,Y)矩阵字符串</returns>
        static public string ToTable(DataMatrix instance, bool LeftPad = false)
        {
            StringBuilder sb = new StringBuilder();
            IEnumerable<object> data = instance._ptrObj;
            int bitWidth = LambdaUtil.bitWid(Convert.ToInt64(data.Last()));
            for(int index = 0; index < data.Count();)
            {
                var format = string.Format("{0:d"+((LeftPad)?0:bitWidth)+"}.",data.ElementAt(index));
                sb.Append(format);
                if (++index % instance._matrix.Item1 == 0) sb.AppendLine();
            }
            return sb.ToString();
        }
        /// <summary>
        /// 给一个M44矩阵的16进制码表矩阵
        /// </summary>
        public static DataMatrix internalClass
        {
            get
            {
                IEnumerable<char> ds = HexTable;
                return new DataMatrix(ds.Cast<object>());
            }
        }
    }
}
